import React from 'react';
import { routeManager } from '@/utils/routeManager';
import { RouteConfig } from '@/config/routes';
import { MenuItem } from '@/types';

/**
 * 路由辅助工具类
 * 提供便捷的路由添加、删除和管理功能
 */
export class RouteHelper {
  /**
   * 快速添加页面路由
   * @param path 路由路径
   * @param componentPath 组件路径（相对于pages目录）
   * @param title 页面标题
   * @param options 其他选项
   */
  static addPageRoute(
    path: string,
    componentPath: string,
    title: string,
    options: {
      requireAuth?: boolean;
      permission?: string;
      exact?: boolean;
    } = {}
  ): void {
    const config: RouteConfig = {
      path,
      component: React.lazy(() => import(`@/pages/${componentPath}`)),
      exact: options.exact,
      meta: {
        title,
        requireAuth: options.requireAuth !== false, // 默认需要认证
        permission: options.permission,
      },
    };

    routeManager.addRouteConfig(config);
  }

  /**
   * 批量添加路由
   * @param routes 路由配置数组
   */
  static addBatchRoutes(routes: Array<{
    path: string;
    componentPath: string;
    title: string;
    requireAuth?: boolean;
    permission?: string;
  }>): void {
    routes.forEach(route => {
      this.addPageRoute(route.path, route.componentPath, route.title, {
        requireAuth: route.requireAuth,
        permission: route.permission,
      });
    });
  }

  /**
   * 从菜单配置自动生成路由
   * @param menuItems 菜单配置
   */
  static generateRoutesFromMenu(menuItems: MenuItem[]): void {
    const processMenuItem = (item: MenuItem) => {
      if (item.path && item.label) {
        // 根据路径推断组件路径
        const componentPath = this.pathToComponentPath(item.path);
        
        this.addPageRoute(item.path, componentPath, item.label, {
          requireAuth: true,
          permission: item.permission,
        });
      }

      // 处理子菜单
      if (item.children) {
        item.children.forEach(processMenuItem);
      }
    };

    menuItems.forEach(processMenuItem);
  }

  /**
   * 将路由路径转换为组件路径
   * @param path 路由路径
   * @returns 组件路径
   */
  private static pathToComponentPath(path: string): string {
    // 移除开头的斜杠
    const cleanPath = path.startsWith('/') ? path.slice(1) : path;
    
    // 将路径转换为驼峰命名
    const parts = cleanPath.split('/');
    const componentPath = parts.map(part => {
      // 将kebab-case转换为PascalCase
      return part.split('-').map(word => 
        word.charAt(0).toUpperCase() + word.slice(1)
      ).join('');
    }).join('/');

    return componentPath;
  }

  /**
   * 移除路由
   * @param path 路由路径
   */
  static removeRoute(path: string): void {
    routeManager.removeRouteConfig(path);
  }

  /**
   * 获取所有路由信息
   */
  static getAllRoutes(): RouteConfig[] {
    return routeManager.getRouteConfigs();
  }

  /**
   * 获取路由统计信息
   */
  static getRouteStats() {
    const allRoutes = routeManager.getRouteConfigs();
    const authRoutes = routeManager.getAuthRoutes();
    const publicRoutes = routeManager.getPublicRoutes();

    return {
      total: allRoutes.length,
      authenticated: authRoutes.length,
      public: publicRoutes.length,
      routes: allRoutes.map(route => ({
        path: route.path,
        title: route.meta?.title,
        requireAuth: route.meta?.requireAuth,
        permission: route.meta?.permission,
      })),
    };
  }

  /**
   * 验证路由配置
   */
  static validateRoutes(): {
    valid: boolean;
    errors: string[];
  } {
    const errors: string[] = [];
    const routes = routeManager.getRouteConfigs();
    const paths = new Set<string>();

    routes.forEach((route, index) => {
      // 检查重复路径
      if (paths.has(route.path)) {
        errors.push(`Duplicate route path: ${route.path}`);
      }
      paths.add(route.path);

      // 检查必要字段
      if (!route.path) {
        errors.push(`Route at index ${index} missing path`);
      }

      if (!route.component) {
        errors.push(`Route at index ${index} missing component`);
      }
    });

    return {
      valid: errors.length === 0,
      errors,
    };
  }

  /**
   * 调试信息：打印所有路由
   */
  static debugRoutes(): void {
    console.group('🛣️ Route Debug Information');
    
    const stats = this.getRouteStats();
    console.log('📊 Route Statistics:', stats);
    
    const validation = this.validateRoutes();
    console.log('✅ Route Validation:', validation);
    
    console.groupEnd();
  }
}

// 导出便捷方法
export const addRoute = RouteHelper.addPageRoute;
export const removeRoute = RouteHelper.removeRoute;
export const getRouteStats = RouteHelper.getRouteStats;
export const debugRoutes = RouteHelper.debugRoutes; 